package rsj.dao;

import java.sql.Connection;
import java.sql.Date;
import java.sql.SQLException;
import java.sql.Timestamp;

import common.util.Assert;
import org.apache.commons.lang3.StringUtils;

import rsj.db.dbutils.UniqueID;
import rsj.table.Role;
import rsj.table.RoleType;
import rsj.table.Rome;
import rsj.table.User;
import rsj.table.UserType;

import com.rlyy.aibase.db.QueryRunner;
import com.rlyy.aibase.utils.base.MapNode;
import com.rlyy.aibase.utils.base.Node;
import com.rlyy.aibase.utils.base.TableNode;
import com.rlyy.aibase.utils.helpers.DateHelper;

public class RoleInfoDao {
	
	private static final RoleInfoDao infoDao = new RoleInfoDao();
	
	 public static RoleInfoDao getInstance(){
	        return infoDao;
	 }

	 public void insertRole(Connection conn,String id,String roleName,String funcontent,String status,Date cdate,Timestamp edate) throws SQLException{
		QueryRunner queryRunner = new QueryRunner();
		
		//查询角色编号
		StringBuffer findsql = new StringBuffer();
		findsql.append("select max("+Role.Role_Uid+") Role_Uid from "+ Role.Table_Name);
		TableNode map = queryRunner.queryLinkTableNode(conn,findsql.toString());
		String uid =  map.getValues(Role.Role_Uid)[0]; 
		String uidnew = "RJC001";
		if(StringUtils.isNoneBlank(uid)){
			String ridnew = putong(Integer.valueOf(uid.substring(3))+1);
			uidnew =  uid.substring(0, 3)+ridnew;
		}	
		
		 StringBuffer countsql = new StringBuffer();
		 countsql.append("select count(1) from "+Role.Table_Name+" where "+Role.Role_Name+" = ?");
	     Node node = queryRunner.queryLinkNode(conn, countsql.toString(),roleName);
	     int count = node.valueInt();
	    	
	     Assert.isTrue(count == 0, "角色名已经存在，不能添加！");
		
		//增加角色
	    StringBuffer rolesql = new StringBuffer();
	    rolesql.append("insert into "+Role.Table_Name+" ("+Role.Role_Id+","+Role.Role_Name+","+Role.Role_Funcontent+","+Role.Role_Uid+",")
	    		.append(Role.Role_Ctime+","+Role.Role_Utime+","+Role.Role_Status)
	    		.append(")values(?,?,?,?,?,?,?)");
	    	
	    queryRunner.update(conn,rolesql.toString(),id,roleName,funcontent,uidnew,cdate,edate,status);
	 }
	 
	 public int checkRoleName(Connection conn,String roleName) throws SQLException{
		 QueryRunner queryRunner = new QueryRunner();
		 StringBuffer findsql = new StringBuffer();
		 findsql.append("select count(1) from "+Role.Table_Name+" where "+Role.Role_Name+" = ?");
		 Node node = queryRunner.queryLinkNode(conn, findsql.toString(),roleName);
		 int count = node.valueInt();
		 
		 return count;
	 }
	 
	 public void insertRome(Connection conn,String roleId,String menuids )throws SQLException{
		 QueryRunner queryRunner = new QueryRunner();
		 Object params[][] = new Object[menuids.split(",").length][];
		 for(int i=0;i<menuids.split(",").length;i++){
	    		String arr[] = new String[3];
	    		arr[0] = String.valueOf(UniqueID.generateId());
	    		arr[1] = roleId;
	    		arr[2] = menuids.split(",")[i];   		
	    		params[i] = arr;
	    	}
		 
		 StringBuffer romesql = new StringBuffer();
	     romesql.append("insert into "+Rome.Table_Name+" ("+Rome.Rome_Id+","+Rome.Rome_Role_Id+","+Rome.Rome_Menu_Id);
	     romesql.append(")values(?,?,?)");
	     queryRunner.batch(conn, romesql.toString(), params);
	 }
	 
	 public TableNode findAllRole(Connection conn)throws SQLException{
		 QueryRunner queryRunner = new QueryRunner();
		 StringBuffer findsql = new StringBuffer();
		 findsql.append("select "+Role.Role_Id+","+Role.Role_Name+" from "+Role.Table_Name);
		 findsql.append(" where role_status = ").append(" '1' ");
		 return  queryRunner.queryLinkTableNode(conn,findsql.toString());
	 }
	 
	 public MapNode findRoleList(Connection conn,int size,int pcount) throws SQLException{
		 
		 QueryRunner queryRunner = new QueryRunner();
	     MapNode responsedata = new MapNode(); 
	     StringBuffer countsql = new StringBuffer();
	     
	     countsql.append("select count(1) from "+Role.Table_Name);
	     Node node = queryRunner.queryLinkNode(conn, countsql.toString()); 	
	     int count = node.valueInt();
	 	 responsedata.putNode("User_Count", String.valueOf(count));
    	 if(count == 0){  		
    		 responsedata.putNode("User_List", "");
    		 return responsedata;
    		
    	 }
    	 StringBuffer sql = new StringBuffer();
    	 sql.append("select "+Role.Role_Id+", "+Role.Role_Name+" , "+Role.Role_Funcontent+", "+Role.Role_Uid+", "+Role.Role_Status+" from "+Role.Table_Name )
    	 	 .append( " order by "+Role.Role_Utime+" desc limit ? Offset ?");
    	 
    	 TableNode map = queryRunner.queryLinkTableNode(conn,sql.toString(),size,size*(pcount-1));
    	 responsedata.putNode("Role_List", map.toJson());			
		 return responsedata;
	     
	 }
	 
	 public String putong(int num) {		    
		if (num < 10) {
		   return "00" + num;
		} else if (num >= 100) {
		   return num+"";
		} else{
		   return "0"+num;  
		}
		        		    
	 }
	 
	 public void updateRole(Connection conn,String id,String roleName,String funcontent,String status,Timestamp udate) throws SQLException{
		 QueryRunner queryRunner = new QueryRunner();
		 StringBuffer findsql = new StringBuffer();
		 findsql.append("select count(1) from ").append(Role.Table_Name).append(" where ")
			 	 .append(Role.Role_Id+" != ? and ").append(Role.Role_Name +" =?");
		 Node node = queryRunner.queryLinkNode(conn, findsql.toString(),id,roleName); 	
		 int count = node.valueInt();
		 Assert.isTrue(count == 0, "用户名已经存在，不能修改！");
		 
		 //如果修改角色状态为停用，判断该角色有无用户，有用户不让修改
		 if(RoleType.Role_Status_Stop.equals(status)){
			 StringBuffer countsql = new StringBuffer();
			 countsql.append("select count(1) from "+User.Table_Name+" where "+User.User_Status+" = ? and "+User.User_Role_Id+" = ?");
			 Node node1 = queryRunner.queryLinkNode(conn, countsql.toString(),UserType.user_status_normal,id); 	
			 int count1 = node1.valueInt();
			 Assert.isTrue(count1 == 0, "该角色下存在用户，不能停用！");
		 }
		 
		 StringBuffer updatesql = new StringBuffer();
		 updatesql.append("update "+Role.Table_Name+" set "+Role.Role_Name+" = ?,")
		 			.append(Role.Role_Funcontent+" = ?,")
		 			.append(Role.Role_Utime+" = ?,")
		 			.append(Role.Role_Status+" = ?")
		 			.append(" where "+Role.Role_Id+" = ?");
		 
		 queryRunner.update(conn,updatesql.toString(),roleName,funcontent,udate,status,id);
	 }
	 
	 public void delRome(Connection conn,String id)throws SQLException{
		 QueryRunner queryRunner = new QueryRunner();
		 StringBuffer updatesql = new StringBuffer();
		 updatesql.append("delete from "+Rome.Table_Name+" where "+Rome.Rome_Role_Id+" = ?");
		 queryRunner.update(conn,updatesql.toString(),id);
	 }
	 
	 public MapNode roleById(Connection conn,String id)throws SQLException{
		 QueryRunner queryRunner = new QueryRunner();
		 StringBuffer findsql = new StringBuffer();
		 findsql.append("select "+Role.Role_Id+","+Role.Role_Name+","+Role.Role_Funcontent+","+Role.Role_Status+",")
		 		.append("(select string_agg("+Rome.Rome_Menu_Id+",',') Menu_Ids from "+Rome.Table_Name+" where "+Rome.Rome_Role_Id+" = ?)")
		 		.append("from "+Role.Table_Name+" where "+Role.Role_Id+" = ?");
		 MapNode map = queryRunner.queryLinkRow(conn,findsql.toString(),id,id);
	     return map;
		 
	 }
	 
	 public void updateRoleStatus(Connection conn,String id,String status)throws SQLException{
		 QueryRunner queryRunner = new QueryRunner();
		 StringBuffer upsql = new StringBuffer();
		 
		 upsql.append("update "+Role.Table_Name+" set "+Role.Role_Status+" = ? ,"+Role.Role_Utime+" = ? where "+Role.Role_Id+" = ?");
		 queryRunner.update(conn,upsql.toString(),status,DateHelper.strToTimestamp(DateHelper.getDate(new java.util.Date())),id);
	 }
		
}
